import 'dart:async';

import 'package:http/http.dart' as http;
import 'dart:convert';

import 'loader.dart';
import 'package:catsao/entity/news_item_entity.dart';
import 'package:catsao/util/sp_helper.dart';
import 'package:catsao/db/news_dao.dart';
import 'package:catsao/util/log_helper.dart';

class NewsLoader extends Loader<NewsItemEntity> {
  static NewsLoader _instatnce = new NewsLoader._internal();
  static String type = null;
  static String spLoadTimeKey = null;
  static String tabName = null;

  final String TAG = 'NewsLoader';
  final String JUHE_API_KEY = '3a86f36bd3ecac8a51135ded5eebe862';

  // final String NEWS_URL = 'https://v.juhe.cn/toutiao/index?';

  // final String NEWS_URL =  "http://192.168.3.7:8089/portal/newsV2/getNewsList.action?";

  final String NEWS_URL =
      "https://www.wcscshop.com/portal/newsV2/getNewsList.action?";
  final String NEWS_IMAGE_URL = "https://www.wcscshop.com/uploadFile";

  final int pageNo = 1;
  final int pageSize = 20;
  final bool isDclick = false;
  final bool fetchPageCount = false;
  final List sorts = ["updateTime"];

  int lastLoadTime = null;
  List<NewsItemEntity> data = [];

  factory NewsLoader(Map<String, String> options) {
    type = options['type'];
    spLoadTimeKey = options['spLoadTimeKey'];
    tabName = options['tabName'];
    return _instatnce;
  }

  SharedPreferenceHelper spHelper = null;

  NewsLoader._internal() {
    spHelper = new SharedPreferenceHelper();
  }

  @override
  Future<List<NewsItemEntity>> loadData(
      {DataSource datasource: DataSource.DEFAULT,
      int offset,
      int limit,
      int newsType}) async {
    if (data != null) {
      data.clear();
    } else {
      data = [];
    }

    if (datasource == DataSource.DEFAULT) {
      await _loadDataFromNetwork(newsType);
      // await _loadDataFromDB(offset, limit);
      try {
        if (data == null) {
          data = [];
          await _loadDataFromNetwork(newsType);
        }
        lastLoadTime = spHelper.getInt(spLoadTimeKey);
      } catch (ex) {
        Log.i(TAG, ex.toString());
        data = null;
      }
    } else if (datasource == DataSource.NETWORK) {
      try {
        await _loadDataFromNetwork(newsType);
        lastLoadTime = spHelper.getInt(spLoadTimeKey);
      } catch (ex) {
        Log.i(TAG, ex.toString());
        data = null;
      }
    } else if (datasource == DataSource.DATABASE) {
      try {
        await _loadDataFromDB(offset, limit);
      } catch (ex) {
        Log.i(TAG, ex.toString());
        data = null;
      }
    }

    /*Log.i(TAG, 'news type ${tabName}, lastLoadTime=${lastLoadTime}');
    try {
      if (lastLoadTime == null || new DateTime.now().millisecondsSinceEpoch - lastLoadTime > 1000 * 60 * 60) {
        await _loadDataFromNetwork();
      } else {
        await _loadDataFromDB();
      }
    } catch(ex) {
      Log.i(TAG, ex.toString());
      data = null;
    }*/
    return data;
  }

  init() async {
    await spHelper.init();
  }

  _formatUrl(int newsType) {
    return '${NEWS_URL}news_type=${newsType}&pageNo=${pageNo}&pageSize=${pageSize}&isDclick=${isDclick}&fetchPageCount=${fetchPageCount}&sorts=${sorts}';
  }

  _loadDataFromDB(int offset, int limit) async {
    data = await new NewsDao().getNewsByOffset(tabName, offset, limit);
  }

  _loadDataFromNetwork(int newsType) async {
    //http.Response response = await http.get(_formatUrl());
    http.Response response = await http.get(Uri.parse(_formatUrl(newsType)));
    Log.i(TAG, 'news type ${tabName} response :\n ${response.body}');
    _parseResponse(response);
    new NewsDao().insertBatch(data);
    // spHelper.setInt(spLoadTimeKey, new DateTime.now().millisecondsSinceEpoch);
  }

  _parseResponse(http.Response response) {
    Map map = jsonDecode(response.body);
    Map result = map['data'];
    String stat = map['code'];

    if (stat == "200") {
      Log.i(TAG, 'code == 1, this respones is ok!');
      List d = result['data'];
      for (int i = 0; i < d.length; i++) {
        Map item = d[i];
        String content = item['content'];
        content = content.replaceAll("/uploadFile", NEWS_IMAGE_URL);
        data.add(new NewsItemEntity(
            newsid: item['id'],
            title: item['title'],
            humanableDate: item['pushTime'],
            news_imgPath: NEWS_IMAGE_URL + item['news_imgPath'],
            content: content));
      }
    }
    Log.i(TAG, 'parseReponse data: ${data.length}');
  }
}
